package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Instituicao;

public class InstituicaoDaoImpl implements InstituicaoDao {
	Connection c;

	public InstituicaoDaoImpl() {
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}

	@Override
	public void salvaInstituicao(Instituicao instituicao) throws SQLException {
		String sql = "INSERT INTO instituicoes VALUES (?,?,?,?,?,?,?)";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, instituicao.getIdInstituicao());
		ps.setString(2, instituicao.getNomeInstituicao());
		ps.setString(3, instituicao.getEndereco());
		ps.setInt(4, instituicao.getNum());
		ps.setInt(5, instituicao.getCep());
		ps.setString(6, instituicao.getBairro());
		ps.setString(7, instituicao.getComplemento());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaInstituicao(Instituicao instituicao) throws SQLException {
		String sql = "UPDATE instituicoes SET nomeInstituicao = ?, "
				+ "endereco = ?, " + "num = ?, " + "cep = ?, " + "bairro = ?, "
				+ "complemento = ? WHERE idInstituicao = ?";
		PreparedStatement ps = c.prepareStatement(sql);

		ps.setString(1, instituicao.getNomeInstituicao());
		ps.setString(2, instituicao.getEndereco());
		ps.setInt(3, instituicao.getNum());
		ps.setInt(4, instituicao.getCep());
		ps.setString(5, instituicao.getBairro());
		ps.setString(6, instituicao.getComplemento());
		ps.setInt(7, instituicao.getIdInstituicao());

		ps.execute();
		ps.close();

	}

	@Override
	public void excluiInstituicao(Instituicao instituicao) throws SQLException {
		String sql = "DELETE instituicoes WHERE idInstituicao = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, instituicao.getIdInstituicao());
		ps.execute();
		ps.close();

	}

	@Override
	public Instituicao pesquisaInstituicao(Instituicao instituicao)
			throws SQLException {
		Instituicao in = new Instituicao();
		String sql = "SELECT idInstituicao, nomeInstituicao, endereco, "
				+ "num, cep, bairro, complemento FROM instituicoes "
				+ "WHERE idInstituicao = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, instituicao.getIdInstituicao());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			in.setIdInstituicao(rs.getInt("idInstituicao"));
			in.setNomeInstituicao(rs.getString("nomeInstituicao"));
			in.setEndereco(rs.getString("endereco"));
			in.setNum(rs.getInt("num"));
			in.setCep(rs.getInt("cep"));
			in.setBairro(rs.getString("bairro"));
			in.setComplemento(rs.getString("complemento"));
		}
		ps.close();
		rs.close();
		return in;

	}

}
